#include "XDemuxThread.h"
#include "XDemux.h"
#include "XVideoThread.h"
#include "XAudioThread.h"
#include <QDebug>
struct AVPacket;
bool XDemuxThread::Open(const char * url, IVideoCall * call)
{
	if (url == NULL) {
		return false;
	}
	demux_thread_mutex.lock();
	
	//打开解封装
	bool ret = demux->Open(url);
	if (!ret) {
		qDebug() << "demux->open failed";
		return false;
	}
	//打开视频解码器和处理线程
	if (vt->Open(demux->CopyVPara(), call, demux->width, demux->height) == false) {
		ret = false;
		qDebug() << "vt->Open failed";
	}
	//打开音频解码器和处理线程
	if (!at->Open(demux->CopyAPara(), demux->sampleRate, demux->channels)) {
		ret = false;
		qDebug() << "at->Open failed";
	}
	demux_thread_mutex.unlock();
	qDebug() << "XdemuxThread::Open" << ret;
	return ret;
}

void XDemuxThread::Start()
{
	demux_thread_mutex.lock();
	//启动当前线程
	if (!demux) {
		demux = new XDemux();
	}
	if (!vt) {
		vt = new XVideoThread();
	}
	if (!at) {
		at = new XAudioThread();
	}
	QThread::start();
	if (vt) {
		vt->start();
	}
	if (at) {
		at->start();
	}
	demux_thread_mutex.unlock();
}

void XDemuxThread::run()
{
	while (!isExit) {
		demux_thread_mutex.lock();
		if (!demux) {
			demux_thread_mutex.unlock();
			msleep(5);
			continue;
		}

		//音视频同步
		if (vt && at) {
			vt->synpts = at->pts;
		}

		AVPacket *pkt = demux->Read();
		if (!pkt) {
			demux_thread_mutex.unlock();
			msleep(5);
			continue;
		}
		if (demux->IsAudio(pkt)) {
			if (at != NULL) {
				at->Push(pkt);
			}
		}
		else {
			if (vt != NULL) {
				vt->Push(pkt);
			}
			
		}
		demux_thread_mutex.unlock();
	}
}

XDemuxThread::XDemuxThread()
{
}

XDemuxThread::~XDemuxThread()
{
	isExit = true;
	wait();
}
